'use strict';

const BaseController = require('../core/base');

class DictTypeController extends BaseController {
  // 获取字典类型信息
  async dictTypeForm() {
    const query = this.ctx.params;
    const { dictType } = this.ctx.service;
    const result = await dictType.findOne(query);
    if (result) {
      this.success(result);
    } else {
      this.fail();
    }
  }
  async findOne() {
    const { query } = this.ctx.request;
    const { dictType } = this.ctx.service;
    const result = await dictType.findOne(query);
    if (result) {
      this.success(result);
    } else {
      this.fail();
    }
  }
  async list() {
    // { name }
    const query = this.ctx.request.query;
    const { dictType } = this.ctx.service;
    const result = await dictType.find(query);
    this.success(result);
  }

  //   添加和编辑
  async save() {
    const { name, code } = this.ctx.request.body;
    const { id } = this.ctx.params;
    // 校验
    if (!name) return this.fail('字典名称不能为空');
    if (!code) return this.fail('字典编码不能为空');
    const data = this.ctx.request.body;
    const { dictType } = this.ctx.service;
    if (!id) {
      const result = await dictType.save(data);
      if (!result) {
        return this.fail('新增失败');
      }
      this.success();
    } else {
      data.id = id;
      const result = await dictType.save(data);
      if (!result) {
        return this.fail('更新失败');
      }
      this.success();
    }
  }

  // 删除
  async remove() {
    let { ids } = this.ctx.params;
    ids = typeof ids === 'string' ? ids.split(',').map(v => Number(v)) : [];
    const { dictType } = this.ctx.service;
    let count = 0;
    if (ids.length) {
      for (const id of ids) {
        const ret = await dictType.remove(id);
        if (ret) count += 1;
      }
      this.success(count, `共删除${count}条数据`);
    } else {
      this.fail('参数错误');
    }
  }
}


module.exports = DictTypeController;
